class StaticPagesController < ApplicationController
  def home
  end

  def data
    time_type = params[:time_type].to_i

    start_date = params[:start_date]
    end_date = params[:end_date]
    if time_type == 1
      start_date ||= DateTime.parse((Time.zone.now).to_s).strftime('%Y-%m-%d').to_s
      end_date ||= DateTime.parse((Time.zone.now).to_s).strftime('%Y-%m-%d').to_s
    elsif time_type == 3
      start_date ||= DateTime.parse((Time.zone.now-7.days).to_s).strftime('%Y-%m-%d').to_s
      end_date ||= DateTime.parse((Time.zone.now).to_s).strftime('%Y-%m-%d').to_s
    end

    @total = nil

    sql = <<-SQL
      max(campaign_rpts.rpt_date) as rpt_date,sum(campaign_rpts.view_num) as view_num,sum(campaign_rpts.click_num) as click_num,sum(campaign_rpts.cost) as cost
    SQL

    @rpts = CampaignRpt.where(user_id: current_user.id).where(rpt_date:start_date+' 00:00:00'..end_date+ ' 23:59:59').group(:rpt_year,:rpt_month,:rpt_day).select("#{sql}").order(created_at: :desc)
    @total = CampaignRpt.where(user_id: current_user.id).where(created_at:start_date+' 00:00:00'..end_date+ ' 23:59:59').select('sum(campaign_rpts.view_num) as view_num,sum(campaign_rpts.click_num) as click_num,sum(campaign_rpts.cost) as cost').first

    @pv, @pc, @date = [],[],[]
    @rpts&.each do |rpt|
      @pv << rpt.view_num
      @pc << rpt.click_num
      @date << DateTime.parse(rpt.rpt_date.to_s).strftime('%Y-%m-%d').to_s
    end
    render :data, layout: false

  end

end
